<?php
/**
 * Created by PhpStorm.
 * User: WYJ
 * Date: 2018/5/8
 * Time: 15:39
 */

namespace zhtfrontend\controllers;

use common\components\helpers\Fun;
use common\models\datas\Cate;
use doumiaoduo\buildform\BuildForm;
use yii\data\Pagination;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\web\BadRequestHttpException;
use yii\web\Response;
use yii\widgets\ActiveForm;
use zhtfrontend\components\bases\BaseController;
use common\components\actions\DeleteAction;
use zhtfrontend\models\datas\Admin;
use zhtfrontend\models\datas\CustomerReturnVisit;

class ReturnvisitController extends BaseController
{

    //列表
    public function actionIndex()
    {

        $site_id = Fun::getSiteId();

        $param['searchData'] = \Yii::$app->request->get();
        $model = [];
        $pageSize = isset($param['pageSize']) ? $param['pageSize'] : 12;
        $data = CustomerReturnVisit::find()->where(['site_id' => $site_id]);

        $category = (new Query())->select('id,name')->from('{{%cate}}')->where(['parent_id' => 0])->all();

        if (!empty($param['searchData'])) {
            $search_data = array_filter($param['searchData']);
            //手机号搜索
            if (!empty($search_data['tel'])) {
                $data->andWhere(['mobile' => $search_data['tel']]);
            }
            //姓名搜索
            if (!empty($search_data['name'])) {
                $data->andWhere(['name' => $search_data['name']]);
            }
            //意向分类搜索
            if (!empty($search_data['category_id'])) {
                $data->andWhere(['category_id' => $search_data['category_id']]);
            }
            //获客渠道搜索
            if (!empty($search_data['source'])) {
                $data->andWhere(['type' => $search_data['type']]);
            }
            //客户类型搜索
            if (!empty($search_data['status'])) {
                $data->andWhere(['status' => $search_data['status']]);
            }
        }
        if (isset(\Yii::$app->user->identity) && \Yii::$app->user->identity->role == 'customer_manager') {
            $data->andWhere(['admin_id' => \Yii::$app->user->identity->id]);;
        }
        $pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => $pageSize]);
        isset($param['page']) ? $pages->page = $param['page'] - 1 : 0;
        if (isset(\Yii::$app->user->identity) && in_array(\Yii::$app->user->identity->role, ['admin', 'administrator'])) {
            $model = $data->offset($pages->offset)->limit($pages->limit)->all();
        } else {
            if (!empty($param['searchData']['tel']) || !empty($param['searchData']['name'])) $model = $data->all();
        }
        $array = Fun::asArray($model, [
            'id', 'name', 'mobile', 'category_id', 'status', 'admin_id', 'operate', 'is_customer', 'is_student', 'is_buy', 'created_at', 'next_time', 'type', 'details', 'results'
        ]);
        return $this->render('index', [
            'data' => $array,
            'pages' => $pages,
            'category' => $category
        ]);

    }

    //添加
    public function actionCreate()
    {

        $this->layout = '@app/views/layouts/iframe.php';
        $model = new CustomerReturnVisit();
        // $model->scenario = 'create';
        $model->site_id = Fun::getSiteId();
        $form = new BuildForm('@app/components/forms/returnvisitForm.php');
        $form->loadModel(['returnvisit' => $model]);
        $site_id = Fun::getSiteId();

        //分类类别
        $category = Cate::find()->where(['parent_id' => 0])->asArray()->all();
        $form->setItems('returnvisit', 'category_id', ArrayHelper::map($category, 'id', 'name'));

        //负责人
        $admin = Admin::find()->where(['role' => 'customer_manager'])->all();
        $form->setItems('returnvisit', 'admin_id', ArrayHelper::map($admin, 'id', 'name'));

        //客户来源
        $type_arr = [
            ['id' => '0', 'name' => '电话'],
            ['id' => '1', 'name' => '约谈'],
            ['id' => '2', 'name' => '其他']
        ];
        $form->setItems('returnvisit', 'type', ArrayHelper::map($type_arr, 'id', 'name'));
        //客户类别
        $status_arr = [
            ['id' => '0', 'name' => '潜在客户'],
            ['id' => '1', 'name' => '意向客户'],
            ['id' => '2', 'name' => '正式VIP']
        ];
        $form->setItems('returnvisit', 'status', ArrayHelper::map($status_arr, 'id', 'name'));


        //ajax 验证操作,
        if (\Yii::$app->request->post('ajax') == 'returnvisit-form' && $form->loadData(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($form->loadData(\Yii::$app->request->post()) && $form->validate()) {
            $model = $form->getModel('returnvisit');
            $model->site_id = $site_id;
            foreach ($type_arr as $k => $v) {
                if ($v['id'] == $model->type) $type = $v['name'];
            }
            $model->type = $type;
            $model->created_at = strtotime(\Yii::$app->request->post()['CustomerReturnVisit']['created_at']);
            $model->next_time = strtotime(\Yii::$app->request->post()['CustomerReturnVisit']['next_time']);

            if ($model->save(false)) {
                return $this->redirectMessage('添加成功', Fun::url(['returnvisit/index']));
            }

        }
        return $this->render('create', ['form' => $form->render()]);

    }

    //修改
    public function actionUpdate()
    {

        return $this->render('update');

    }

    //删除
    public function actions()
    {
        return [
            'delete' => [
                'class' => DeleteAction::className(),
                'modelClass' => CustomerReturnVisit::className(),
                'message' => ['success' => '删除成功！'],
                'redirectTo' => 'returnvisit/index',
            ],
        ];
    }

}